Android 关于XmlResourceParser

我们先看看XmlResourceParser 类:

/**
 * The XML parsing interface returned for an XML resource.  This is a standard
 * XmlPullParser interface, as well as an extended AttributeSet interface and
 * an additional close() method on this interface for the client to indicate
 * when it is done reading the resource.
 */
public interface XmlResourceParser extends XmlPullParser, AttributeSet, AutoCloseable {
    /**
     * Close this interface to the resource.  Calls on the interface are no
     * longer value after this call.
     */
    public void close();
}

该类的解释为:

为XML资源返回的XML解析接口,这是一个标准XmlPullParser接口,同时继承AttributeSet接口以及当用户完成资源读取时调用的close接口,简单来说就是一个xml资源解析器,用于解析xml资源。

那么该类的作用是什么?

我们知道Activity的setContentView()其实调用的是PhoneWindow里面的setContentView

@Override
    public void setContentView(int layoutResID) {
        // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
        // decor, when theme attributes and the like are crystalized. Do not check the feature
        // before this happens.
        if (mContentParent == null) {
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);
        } else {
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }

    @Override
    public void setContentView(View view) {
        setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
    }

我们可以看到接口

mLayoutInflater.inflate(layoutResID, mContentParent);

将activity传递进来的layoutResID即布局ID,加载到mContentParent里面去。

接着我们进到LayoutInflater的inflate接口可以看到

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        if (DEBUG) {
            Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                    + Integer.toHexString(resource) + ")");
        }

        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

里面调用了一个:

final XmlResourceParser parser = res.getLayout(resource); 

并且再通过

 public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;

            try {
                // Look for the root node.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }

                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }

                final String name = parser.getName();

                if (DEBUG) {
                    System.out.println("**************************");
                    System.out.println("Creating root view: "
                            + name);
                    System.out.println("**************************");
                }

                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        if (DEBUG) {
                            System.out.println("Creating params from root: " +
                                    root);
                        }
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }

                    if (DEBUG) {
                        System.out.println("-----> start inflating children");
                    }

                    // Inflate all children under temp against its context.
                    rInflateChildren(parser, temp, attrs, true);

                    if (DEBUG) {
                        System.out.println("-----> done inflating children");
                    }

                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // Decide whether to return the root that was passed in or the
                    // top view found in xml.
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch (XmlPullParserException e) {
                final InflateException ie = new InflateException(e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } catch (Exception e) {
                final InflateException ie = new InflateException(parser.getPositionDescription()
                        + ": " + e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;

                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }

            return result;
        }
    }

返回view

这里最终会走到一个方法,在这个方法里面进行处理

void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {

        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;

        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

            if (type != XmlPullParser.START_TAG) {
                continue;
            }

            final String name = parser.getName();

            if (TAG_REQUEST_FOCUS.equals(name)) {
                pendingRequestFocus = true;
                consumeChildElements(parser);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else {
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflateChildren(parser, view, attrs, true);
                viewGroup.addView(view, params);
            }
        }

        if (pendingRequestFocus) {
            parent.restoreDefaultFocus();
        }

        if (finishInflate) {
            parent.onFinishInflate();
        }
    }

我们知道XmlPullParser是安卓内置的一个XML解析器,用于解析XML文件,同时我们的布局文件也是一种XML格式文件,通过XmlPullParser解析整个布局文件,解析其中定义的View,例如LinearLayout和FrameLayout等等,再通过AttributeSet attrs = Xml.asAttributeSet(parser)来获取view定义的属性,并通过createViewFromTag()方法来创建View的实例,且在每次递归完成的时候将这个View添加到父布局中去。


好了,我们粗略过了一遍布局文件的加载过程了,我们由此可大概知道,XmlResourcePareser主要用于解析安卓中的资源文件,例如布局资源文件(layout.xml),动画资源文件(anim.xml)等资源文件,由于其继承XmlPullParser,AttributeSet,因此其同时具有解析xml布局文件和操作xml中定义的属性的作用。

我们打开android.content.res.Resources类查看,其中有以下方法用于获取XmlResourceParser

 public XmlResourceParser getLayout(@LayoutRes int id) throws NotFoundException {
        return loadXmlResourceParser(id, "layout");
    }

public XmlResourceParser getAnimation(@AnimatorRes @AnimRes int id) throws NotFoundException {
        return loadXmlResourceParser(id, "anim");
    }

public XmlResourceParser getXml(@XmlRes int id) throws NotFoundException {
        return loadXmlResourceParser(id, "xml");
    }

开始写代码之前我们先了解一些相关的常量和方法:

  • int START_DOCUMENT = 0 :文档的最开头,尚未读取任何内容
  • int END_DOCUMENT = 1 :到达文档的末尾
  • int START_TAG = 2 :开始解析标签
  • int END_TAG = 3 :结束解析标签
  • int TEXT = 4 :读取字符数据,通过调用getText()可以获得
  • int getDepth() :返回元素的当前深度
  • int getEventType() :返回当前事件的类型(START_TAG,END_TAG,TEXT等)
  • int next() :获取下一个解析事件
  • String getAttributeName (int index) :返回指定属性的本地名称
  • String getName() :返回

我们主要讲解以下接口:

public XmlResourceParser getLayout(@LayoutRes int id)

顾名思义,根据提供的布局资源文件id返回一个可读取布局文件中view相关属性的XmlResourceParser。

我们先定义一个layout文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="#66000000"
    android:layout_width="800dp"
    android:layout_height="800dp"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/iv3"
                android:layout_width="300dp"
                android:layout_height="300dp" />
        </RelativeLayout>

        <ImageView
            android:id="@+id/iv2"
            android:layout_width="200dp"
            android:layout_height="200dp" />
    </RelativeLayout>

    <ImageView
        android:id="@+id/iv1"
        android:layout_width="100dp"
        android:layout_height="100dp" />
</RelativeLayout>
</RelativeLayout>

主要代码为:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        XLog.configure().setLogHeadEnable(false);

        XmlResourceParser parser = getResources().getLayout(R.layout.activity_main);
        try {

            int type;
            //过滤掉END_DOCUMENT和非START_TAG的事件
            while ((type = parser.next())!= XmlPullParser.END_DOCUMENT ) {
                if (type != XmlPullParser.START_TAG){
                    continue;
                }

                StringBuilder stringBuilder = new StringBuilder()
                        .append("current type: ")
                        .append(getType(type))
                        .append("\n")
                        .append("current depth: ")
                        .append(parser.getDepth())
                        .append("\n")
                        .append("current name: ")
                        .append(parser.getName())
                        .append("\n");

                for (int i = 0; i < parser.getAttributeCount(); i++){
                    stringBuilder.append(String.format("第%d个属性 -> ", i+1))
                            .append(parser.getAttributeName(i))
                            .append(" : ")
                            .append(parser.getAttributeValue(i))
                            .append("\n");
                }

                XLog.e(stringBuilder.toString());
            }
        }catch (IOException e){
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } finally {
            parser.close();
        }
    }

    private String getType(int type){
        switch (type){
            case XmlPullParser.START_DOCUMENT:
                return "START_DOCUMENT";

            case XmlPullParser.END_DOCUMENT:
                return "END_DOCUMENT";

            case XmlPullParser.START_TAG:
                return "START_TAG";

            case XmlPullParser.END_TAG:
                return "END_TAG";
        }

        return String.valueOf(type);
    }

}

我们根据深度的定义,


image

获取到该布局文件的深度为:


我们可以看到,深度是从1开始的。

所有的log为:

 
    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 1
    │ current name: RelativeLayout
    │ 第1个属性 -> background : #66000000
    │ 第2个属性 -> layout_width : 800.0dip
    │ 第3个属性 -> layout_height : 800.0dip
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────

    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 2
    │ current name: RelativeLayout
    │ 第1个属性 -> layout_width : -1
    │ 第2个属性 -> layout_height : -1
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 
    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 3
    │ current name: RelativeLayout
    │ 第1个属性 -> layout_width : -1
    │ 第2个属性 -> layout_height : -1
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────

    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 4
    │ current name: ImageView
    │ 第1个属性 -> id : @2131165256
    │ 第2个属性 -> layout_width : 300.0dip
    │ 第3个属性 -> layout_height : 300.0dip
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  
    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 3
    │ current name: ImageView
    │ 第1个属性 -> id : @2131165255
    │ 第2个属性 -> layout_width : 200.0dip
    │ 第3个属性 -> layout_height : 200.0dip
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────

    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 2
    │ current name: ImageView
    │ 第1个属性 -> id : @2131165254
    │ 第2个属性 -> layout_width : 100.0dip
    │ 第3个属性 -> layout_height : 100.0dip
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────

回到问题
那么该类的作用是什么?
你应该知道了吧?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容